class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        results=[]
        def findelement(index,path,val):
            if len(path)==3:
                for i in range(index+1,len(nums)):
                    if nums[i]==val:
                        path.append(nums[i])
                        results.append(path[:])
                        path.pop()
                        return 
            else:
                for i in range(index+1,len(nums)-3+len(path)):
                    if len(path)==2:
                        total=sum([nums[i+k] for k in range(4-len(path))]) 
                        if total>val:
                            #print(total,path,val)
                            break
                    if i==index+1 or nums[i]!=nums[i-1]:
                        path.append(nums[i])
                        findelement(i,path,val-nums[i]) 
                        path.pop()
        for j in range(len(nums)-3):
            if nums[j]+nums[j+1]+nums[j+2]+nums[j+3]>target:
                continue
            if j==0 or nums[j]!=nums[j-1]:
                findelement(j,[nums[j]],target-nums[j])
        return results
            